package com.roin.learn.activiti.controller;

import com.roin.learn.activiti.base.BaseController;
import com.roin.learn.activiti.base.SysConstent;
import com.roin.learn.activiti.entity.Page;
import com.roin.learn.activiti.entity.ResourceResult;
import com.roin.learn.activiti.exception.BusinessException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * Activiti引擎自带的用户组维护
 */
@Controller
@RequestMapping("process/group")
public class ProcessGroupController extends BaseController{
    @Resource
    IdentityService identityService;

    @RequestMapping("")
    public String toGroup(Model model){
        checkLogin();
        return "process/group";
    }

    @RequestMapping("list.json")
    @ResponseBody
    public Page getPage(){
        checkLogin();
        List<Group> groups = identityService.createGroupQuery().orderByGroupName().asc().list();
        return new Page(groups);
    }


    @RequestMapping("add.do")
    @ResponseBody
    public ResourceResult add(GroupEntity group){
        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            identityService.saveGroup(group);
            result.setSuccess(true).setMessage("保存成功！");
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("保存用户组异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }

        return result;
    }
    @RequestMapping("delete.do")
    @ResponseBody
    public ResourceResult delete(String[] ids){
        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            int rows = 0;
            for (String id : ids) {
                try {
                    identityService.deleteGroup(id);
                    rows++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (rows==ids.length)
                result.setSuccess(true).setMessage(String.format("删除成功！"));
            else if (rows<ids.length)
                result.setSuccess(true).setMessage(String.format("成功删除%s个用户组，%s个用户组删除失败！",rows,ids.length-rows));
            else
                result.setMessage("删除失败！");
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("保存用户组异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }

        return result;
    }
    @RequestMapping("update.do")
    @ResponseBody
    public ResourceResult update(GroupEntity group){

        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            if (StringUtils.isEmpty(group.getId()))
                result.setMessage("修改失败,groupId为空！");
            else {
                identityService.saveGroup(group);
                result.setSuccess(true).setMessage("修改成功！");
            }
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("修改用户组异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }
        return result;
    }

    /**
     * 通过用户ID批量将用户加入到指定用户组
     * @param groupId
     * @param userIds
     * @return
     */
    @RequestMapping("addUserByIds.do")
    @ResponseBody
    public ResourceResult addUserByIds(String groupId,String[] userIds){

        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            for (String userId : userIds) {
                try {
                    identityService.createMembership(userId,groupId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            result.setSuccess(true).setMessage("添加成功！");
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("添加用户组用户异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }
        return result;
    }
    /**
     * 通过用户ID批量将用户加入到指定用户组
     * @param groupId
     * @param userIds
     * @return
     */
    @RequestMapping("removeUserByIds.do")
    @ResponseBody
    public ResourceResult removeUserByIds(String groupId,String[] userIds){
        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            for (String userId : userIds) {
                try {
                    identityService.deleteMembership(userId,groupId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            result.setSuccess(true).setMessage("删除成功！");

        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("删除用户组用户异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }
        return result;
    }
}
